package com.xd.springboot.exception;

import com.xd.springboot.entity.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;


@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    private  static  final Logger log= LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /*缺少请求参数*/
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public JsonResult handleHttpMessageNotReadableException(MissingServletRequestParameterException e)
    {
        log.error("缺少请求参数,{}",e.getMessage());
        return new JsonResult("400","缺少必要的请求参数");
    }

    /*处理空指针异常*/
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public JsonResult handleTypeMismatchException(NullPointerException e)
    {
        log.error("空指针异常,{}",e.getMessage());
        return new JsonResult("500", "空指针异常了");
    }


    /*处理自定义异常*/
    @ExceptionHandler(BusinessErrorException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public JsonResult handleBusinessError(BusinessErrorException e)
    {
        String code = e.getCode();
        String msg = e.getMessage();
        return new JsonResult(code,msg);
    }


    /*处理系统异常
    * 一般放在最后
    * */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public JsonResult handleUnexpectedServer(Exception e)
    {
        log.error("其他系统异常,{}",e);
        return new JsonResult("500", "系统异常，请联系管理员");
    }
}
